package com.myCompany.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myCompany.edu.realtime.app.BaseAppV1;
import com.myCompany.edu.realtime.bean.TradeOrderUUBean;
import com.myCompany.edu.realtime.common.Constant;
import com.myCompany.edu.realtime.util.AtguiguUtil;
import com.myCompany.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws07_DwsTradeOrder extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws07_DwsTradeOrder().init(
                4007,
                2,
                "Dws07_DwsTradeOrder",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 封装bean
        SingleOutputStreamOperator<TradeOrderUUBean> beanStream = parseToBean(stream);
        //beanStream.print();
        //开窗聚合
        SingleOutputStreamOperator<TradeOrderUUBean> resultStream = windowAndAgg(beanStream);
        resultStream.print();
        //写入clickhouse
        writeToClickhouse(resultStream);

    }

    private void writeToClickhouse(SingleOutputStreamOperator<TradeOrderUUBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_order_window", TradeOrderUUBean.class));
    }

    private SingleOutputStreamOperator<TradeOrderUUBean> windowAndAgg(SingleOutputStreamOperator<TradeOrderUUBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<TradeOrderUUBean>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner((bean,ts)->bean.getTs()*1000))
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeOrderUUBean>() {
                            @Override
                            public TradeOrderUUBean reduce(TradeOrderUUBean bean1,
                                                           TradeOrderUUBean bean2) throws Exception {
                                bean1.setOrderUuCt(bean1.getOrderUuCt() + bean2.getOrderUuCt());
                                return bean1;
                            }
                        },
                        new ProcessAllWindowFunction<TradeOrderUUBean, TradeOrderUUBean, TimeWindow>() {
                            @Override
                            public void process(Context context,
                                                Iterable<TradeOrderUUBean> iterable,
                                                Collector<TradeOrderUUBean> out) throws Exception {
                                TradeOrderUUBean bean = iterable.iterator().next();
                                bean.setStt(AtguiguUtil.toDateTime(context.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(context.window().getEnd()));
                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<TradeOrderUUBean> parseToBean(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(object -> object.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradeOrderUUBean>() {

                    private ValueState<String> userOrderState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        userOrderState = getRuntimeContext().getState(new ValueStateDescriptor<String>("userState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context context,
                                               Collector<TradeOrderUUBean> out) throws Exception {
                        Long orderUuCt = 0L;

                        Long ts =obj.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);

                        if (!today.equals(userOrderState.value())){
                            userOrderState.update(today);
                            orderUuCt = 1L;
                        }
                        out.collect(new TradeOrderUUBean(
                                "","",
                                orderUuCt,ts
                        ));
                    }
                });
    }
}
